package com.qf.service;

import com.qf.dao.SpitDao;
import com.qf.pojo.Spit;
import com.qf.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.UntypedExampleMatcher;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author 千锋健哥
 */
@Service
public class SpitServiceImpl implements SpitService {

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void insert(Spit spit) {
        //生成唯一ID作为主键
        spit.set_id(String.valueOf(idWorker.nextId()));
        spit.setPublishtime(new Date());
        spitDao.insert(spit);
    }

    @Override
    public void update(Spit spit) {
        spit.setPublishtime(new Date());
        spitDao.save(spit);
    }

    @Override
    public Spit findOne(String id) {
        Optional<Spit> byId = spitDao.findById(id);
        if (byId != null) {
            return byId.get();
        }
        return null;
    }

    @Override
    public List<Spit> findSpitByParam(Spit spit) {

        //创建查询对象
        Query query = new Query();

        //创建查询条件对象, 相当于sql语句中的where
        if (!StringUtils.isEmpty(spit.getUserid())) {
            Criteria criteria = Criteria.where("userid").is(spit.getUserid());
            query.addCriteria(criteria);
        }

        //创建查询条件对象, 相当于sql语句中的where
        if (!StringUtils.isEmpty(spit.getContent())) {
            Criteria criteria = Criteria.where("content").is(spit.getContent());
            query.addCriteria(criteria);
        }

        //查询
        List<Spit> list = mongoTemplate.find(query, Spit.class);

        return list;
    }

    @Override
    public void deleteById(String id) {
        spitDao.deleteById(id);
    }

}
